package com.ruicar.afs.cloud.apply.pre.loan.mq.receiver;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyCustBaseInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOprRecordService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOrderInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyRemindDetailsService;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.NoticeTypeEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ApplyResultInfoDto;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ReconsiderationDto;
import com.ruicar.afs.cloud.common.mq.rabbit.listener.AfsMqBizProcessor;
import com.ruicar.afs.cloud.common.mq.rabbit.message.MqTransCode;
import com.ruicar.afs.cloud.parameter.commom.enums.FormalReviewEnums;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import com.ruicar.afs.cloud.parameter.commom.enums.ResultBooleanEnum;
import com.ruicar.afs.cloud.parameter.commom.enums.WhetherEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 复议
 *
 * @author 耿继辉
 */
@AllArgsConstructor
@Slf4j
@Component
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ApplyReconsiderDealProcessor implements AfsMqBizProcessor<ReconsiderationDto> {
    private final ApplyRecordDetailsService applyRecordDetailsService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyOprRecordService applyOprRecordService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ApplyRemindDetailsService applyRemindDetailsService;

    @Override
    public boolean processMessage(ReconsiderationDto entity) throws Exception {
        if (ObjectUtil.isNotNull(entity.getResultInfoDto())) {
            //true
            if (entity.getResultInfoDto().getResult().equals(ResultBooleanEnum.TRUE.getCode())) {
                this.reconsiderSuccess(entity.getResultInfoDto());
            } else if (entity.getResultInfoDto().getResult().equals(ResultBooleanEnum.FALSE.getCode())) {
                //false
                this.ReconsiderFiled(entity.getResultInfoDto());
            }
        }
        return true;
    }

    @Override
    public MqTransCode getCode() {
        return MqTransCode.AFS_POS_APPLY_CASE_CTM_ASSETS_RECONSIDERATION;
    }

    @Override
    public boolean reQueueOnFail() {
        return false;
    }

    /**
     * 复议成功
     *
     * @param entity
     */
    public void reconsiderSuccess(ApplyResultInfoDto entity) {
        if (StringUtil.isNotEmpty(entity.getNoticeType())) {
            if (NoticeTypeEnum.APPROVALRESULT.getCode().equals(entity.getNoticeType())) {
                ApplyOprRecord applyOprRecord = new ApplyOprRecord();
                //查询复议操作记录,多条复议信息
                List<ApplyOprRecord> list = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                        .eq(ApplyOprRecord::getApplyNo, entity.getApplyNo())
                        .eq(ApplyOprRecord::getApplyType, OrderOprType.RECONSIDER));
                ApplyOrderInfo orderInfoByApplyNo = this.applyOrderInfoService.getOrderInfoByApplyNo(entity.getApplyNo());
                if (CollectionUtil.isNotEmpty(list)) {
                    applyOprRecord = list.get(list.size() - 1);
                }
                //复议申请通过，订单状态变更-复议待提交，可编辑
                if (ResultBooleanEnum.TRUE.getCode().equals(entity.getResult())) {
                    log.info("订单复议已核准，客户信息锁定中......");
                    ApplyCustBaseInfo mainCustBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(entity.getApplyNo(), ApplyConstants.PRINCIPAL_BORROWER);
                    ApplyCustBaseInfo commonBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(entity.getApplyNo(), ApplyConstants.COMMON_BORROWER);
                    ApplyCustBaseInfo guarantorCustBaseInfo = this.applyCustBaseInfoService.getCustBaseInfo(entity.getApplyNo(), ApplyConstants.GUARANTOR);
                    if (CollectionUtil.isNotEmpty(list)) {
                        WorkflowRecordDetails applyRecordDetails = new WorkflowRecordDetails();
                        applyRecordDetails.setApproveDate(new Date());
                        applyRecordDetails.setApproveResult(entity.getApproveDemand());
                        applyRecordDetails.setBusinessNo(String.valueOf(applyOprRecord.getId()));
                        applyRecordDetails.setBusinessType(String.valueOf(OrderOprType.RECONSIDER));
                        applyRecordDetails.setCreateTime(new Date());
                        applyRecordDetails.setCreateBy(mainCustBaseInfo.getCreateBy());
                        this.applyRecordDetailsService.save(applyRecordDetails);
                    }
                    //复议成功，更新状态复议待提交
                    orderInfoByApplyNo.setApplyStatus(ApplyConstants.APPLY_STATUS_REVIEWPENDINGSUBMISSION);
                    //更新复议操作表记录状态为复议待提交
                    applyOprRecord.setApplyStatus(FormalReviewEnums.REVIEWPENDINGSUBMISSION.getCode());
                    applyOprRecord.setApproveDate(new Date());
                    applyOprRecord.setApproveRemarks(entity.getApproveDemand());
                    //正式复议核准之后，更新客户信息is_lock = 1;
                    if (ObjectUtil.isNotNull(mainCustBaseInfo)) {
                        mainCustBaseInfo.setIsLock(WhetherEnum.YES.getIndex());
                        this.applyCustBaseInfoService.updateById(mainCustBaseInfo);
                        log.info("订单复议已核准，主借人信息已锁定......");
                    }
                    if (ObjectUtil.isNotNull(commonBaseInfo)) {
                        commonBaseInfo.setIsLock(WhetherEnum.YES.getIndex());
                        this.applyCustBaseInfoService.updateById(commonBaseInfo);
                        log.info("订单复议已核准，共借人信息已锁定......");
                    }
                    if (ObjectUtil.isNotNull(guarantorCustBaseInfo)) {
                        guarantorCustBaseInfo.setIsLock(WhetherEnum.YES.getIndex());
                        this.applyCustBaseInfoService.updateById(guarantorCustBaseInfo);
                        log.info("订单复议已核准，担保人信息已锁定......");
                    }
                    //保存复议留言
                    ApplyRemindDetails applyRemindDetails = new ApplyRemindDetails();
                    applyRemindDetails.setApplyNo(entity.getApplyNo());
                    applyRemindDetails.setBusinessType(String.valueOf(OrderOprType.RECONSIDER));
                    applyRemindDetails.setCreateBy(mainCustBaseInfo.getCreateBy());
                    applyRemindDetails.setMsgContent(entity.getApproveDemand());
                    applyRemindDetails.setCreateTime(new Date());
                    this.applyRemindDetailsService.save(applyRemindDetails);
                    log.info("复议核准，复议要求已保存......");
                } else if (ResultBooleanEnum.FALSE.getCode().equals(entity.getResult())) {
                    //更新复议操作记录状态为拒绝
                    orderInfoByApplyNo.setApplyStatus(ApplyConstants.APPLY_STATUS_REFUSE);
                    applyOprRecord.setApplyStatus(FormalReviewEnums.REFUSAL.getCode());
                }
                this.applyOprRecordService.updateById(applyOprRecord);
                this.applyOrderInfoService.updateById(orderInfoByApplyNo);
                log.info("申请编号：{}" + entity.getApplyNo() + "申请复议通过");
            } else if (NoticeTypeEnum.FALLLIBRARY.getCode().equals(entity.getNoticeType())) {
                log.info("申请编号:{}" + entity.getApplyNo() + "信审落库成功");
            }
        } else {
            log.info("信审落库了");
        }
    }

    /**
     * 复议失败
     *
     * @param entity
     */
    public void ReconsiderFiled(ApplyResultInfoDto entity) {
        //审批结果
        if (NoticeTypeEnum.APPROVALRESULT.getCode().equals(entity.getNoticeType())) {
            log.info("申请编号：{}" + entity.getApplyNo() + "申请复议失败");
            ApplyOprRecord applyOprRecord = new ApplyOprRecord();
            //更新复议拒绝结果
            List<ApplyOprRecord> list = this.applyOprRecordService.list(Wrappers.<ApplyOprRecord>query().lambda()
                    .eq(ApplyOprRecord::getApplyNo, entity.getApplyNo())
                    .eq(ApplyOprRecord::getApplyType, OrderOprType.RECONSIDER));
            if (CollectionUtil.isNotEmpty(list)) {
                applyOprRecord = list.get(list.size() - 1);
            }
            applyOprRecord.setApplyStatus(FormalReviewEnums.REFUSAL.getCode());
        } else if (NoticeTypeEnum.FALLLIBRARY.getCode().equals(entity.getNoticeType())) {
            //落库结果
            log.info("申请编号:{}" + entity.getApplyNo() + "信审落库失败");
        }
    }
}
